package com.hmdp.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.hmdp.dto.Result;
import com.hmdp.dto.UserDTO;
import com.hmdp.entity.Follow;
import com.hmdp.entity.User;
import com.hmdp.mapper.FollowMapper;
import com.hmdp.service.IFollowService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hmdp.service.IUserService;
import com.hmdp.utils.UserHolder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.Collections;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;


@Service
public class FollowServiceImpl extends ServiceImpl<FollowMapper, Follow> implements IFollowService {

    @Autowired
    private StringRedisTemplate stringRedisTemplate;
    @Autowired
    private IUserService userService;

    @Override
    public Result follow(Long id, Boolean isFollow) {
        Follow follow = new Follow();
        follow.setFollowUserId(id);
        Long user_id = UserHolder.getUser().getId();
        follow.setUserId(user_id);
        String key = "follow:" + user_id;
        if(isFollow){
            // 关注
            boolean save = this.save(follow);
            if(save){
                stringRedisTemplate.opsForSet().add(key,id.toString());
            }
        }else{
            // 取关
            boolean remove = this.remove(new LambdaQueryWrapper<>(Follow.class).eq(Follow::getUserId, user_id)
                    .eq(Follow::getFollowUserId, id));
            if(remove){
                stringRedisTemplate.opsForSet().remove(key,id.toString());
            }
        }
        return Result.ok();
    }

    @Override
    public Result isFollow(Long id) {
        Long count = query().eq("user_id", UserHolder.getUser().getId()).eq("follow_user_id", id).count();
        return Result.ok(count>0);
    }

    @Override
    public Result followCommons(Long id) {
        String key1 = "follow:" + UserHolder.getUser().getId();
        String key2 = "follow:" + id;
        Set<String> intersect = stringRedisTemplate.opsForSet().intersect(key1, key2);
        if(intersect==null || intersect.isEmpty()){
            return Result.ok(Collections.emptyList());
        }
        List<Long> ids = intersect.stream().map(Long::valueOf).collect(Collectors.toList());
        List<User> users = userService.listByIds(ids);
        List<UserDTO> collect = users.stream().map(user -> BeanUtil.copyProperties(user, UserDTO.class)).collect(Collectors.toList());
        return Result.ok(collect);
    }
}
